﻿using Newtonsoft.Json;

namespace MS.Core.JsonConverters
{
    /// <summary>
    /// 表主键 Long 与字符串相互转换
    /// </summary>
    public class LongToStringConverter : JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            return objectType == typeof(long);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="reader"></param>
        /// <param name="objectType"></param>
        /// <param name="existingValue"></param>
        /// <param name="serializer"></param>
        /// <returns></returns>
        /// <exception cref="JsonSerializationException"></exception>
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            long idL = 0;
            if (reader.TokenType == JsonToken.Null)
                return idL;
            try
            {
                if (reader.Value != null)
                {
                    string str = reader.Value.ToString();
                    if (str != string.Empty)
                    {
                        idL = Convert.ToInt64(reader.Value);
                    }
                }
            }
            catch (Exception e)
            {
                throw new JsonSerializationException($"转换失败，将 {reader.Value} 转成long", e);
            }
            return idL;
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            if (value == null)
            {
                // writer.WriteNull();
                writer.WriteValue("");
                return;
            }

            writer.WriteValue(value.ToString());
        }
    }
}
